<template>
  <view class="mine-page">
    <!-- 顶部个人信息 -->
    <view class="profile-section">
      <image class="avatar" src="/static/tabbar/顾客默认头像.png" />
      <view class="user-info">
        <text class="nickname">{{ userInfo.userName || '未登录' }}</text>
      </view>
    </view>

    <!-- 会员卡信息卡片 -->
    <view class="member-card">
      <view class="card-header">
        <view>
          <text class="card-type">会员卡·{{ userInfo.memberName || '普通会员' }}</text>
          <text class="card-number">{{ userInfo.memberCode || '暂无会员号' }}</text>
        </view>
        <image class="qr-icon" src="/static/mine/qr.png" />
      </view>
      <view class="card-info">
        <view class="info-item" @tap="handleCardInfo('coupon')">
          <text class="info-value">{{ userInfo.couponCount || 0 }}</text>
          <text class="info-label">优惠券</text>
        </view>
        <view class="info-item" @tap="handleCardInfo('balance')">
          <text class="info-value">{{ userInfo.surplus || '0.0' }}</text>
          <text class="info-label">余额</text>
        </view>
        <view class="info-item" @tap="handleCardInfo('points')">
          <text class="info-value">{{ userInfo.point || 0 }}</text>
          <text class="info-label">积分</text>
        </view>
      </view>
    </view>

    <!-- 我的功能 -->
    <view class="section-title">我的功能</view>
    <view class="feature-list">
      <view class="feature-item" @tap="handleFeature('discount')">
        <image class="feature-icon" src="/static/mine/discount.jpg" />
        <text>兑换优惠</text>
      </view>
      <view class="feature-item" @tap="handleFeature('service')">
        <image class="feature-icon" src="/static/mine/contact.jpg" />
        <text>联系客服</text>
      </view>
      <view class="feature-item" @tap="handleFeature('address')">
        <image class="feature-icon" src="/static/mine/address.jpg" />
        <text>地址管理</text>
      </view>
      <view class="feature-item" @tap="handleFeature('invoice')">
        <image class="feature-icon" src="/static/mine/invoice.jpg" />
        <text>开发票</text>
      </view>
      <view class="feature-item" @tap="handleFeature('refund')">
        <image class="feature-icon" id="png" src="https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/退货退款.png" />
        <text>退款</text>
      </view>
    </view>

    <!-- 账户设置 -->
    <view class="section-title">账户设置</view>
    <view class="setting-list">
      <view class="setting-item" @tap="handleSetting('profile')">
        <text class="setting-label">个人资料</text>
        <text class="setting-arrow">></text>
      </view>
      <view class="setting-item" @tap="handleSetting('about')">
        <text class="setting-label">关于我们</text>
        <text class="setting-arrow">></text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { mineApi, couponApi } from '../../api/index'

// 用户信息
const userInfo = ref({
  userName: '',
  memberCode: '',
  memberName: '',
  point: 0,
  surplus: 0,
  couponCount: 0
})


// 店铺信息
const storeInfo = ref({
  name: '',
  latitude: null,
  longitude: null,
  distance: '--'
})

// 处理功能点击
const handleFeature = (type) => {
  switch (type) {
    case 'discount':
      // 兑换优惠
      uni.navigateTo({
        url: '/src/pages/mine/discount'
      })
      break
    case 'service':
      // 联系客服
      uni.navigateTo({
        url: '/src/pages/mine/service'
      })
      break
    case 'address':
      // 地址管理
      uni.navigateTo({
        url: '/src/pages/mine/address'
      })
      break
    case 'invoice':
      // 开发票
      uni.navigateTo({
        url: '/src/pages/mine/invoice'
      })
      break
    case 'refund':
      // 退款
      uni.navigateTo({
        url: '/src/pages/mine/refund'
      })
      break
  }
}

// 处理设置点击
const handleSetting = (type) => {
  switch (type) {
    case 'profile':
      // 个人资料
      uni.navigateTo({
        url: '/src/pages/mine/profile'
      })
      break
    case 'about':
      // 关于我们
      uni.navigateTo({
        url: '/src/pages/mine/about'
      })
      break
  }
}

// 处理会员卡信息点击
const handleCardInfo = (type) => {
  switch (type) {
    case 'coupon':
      // 跳转到优惠券页面
      uni.navigateTo({
        url: '/src/pages/mine/coupon'
      })
      break
    case 'balance':
      // 跳转到充值页面，携带余额参数
      uni.navigateTo({
        url: `/src/pages/mine/recharge?balance=${userInfo.value.surplus || 0}`
      })
      break
    case 'points':
      // 跳转到积分页面
      uni.navigateTo({
        url: '/src/pages/mine/discount'
      })
      break
  }
}

// 获取用户信息
const getMyInfo = async () => {
  try {
    const token = uni.getStorageSync('token')
    const res = await mineApi.getMyInfo(token)
    if (res.code === 200) {
      // 映射后端数据到前端显示
      userInfo.value = {
        userName: res.data.用户名,
        memberCode: res.data.会员号,
        memberName: res.data.会员等级,
        point: res.data.积分,
        surplus: res.data.余额,
        couponCount: 0 // 先设为0，由getValidCouponCount方法更新
      }
      
      // 获取优惠券列表并计算未过期的数量
      await getValidCouponCount()
    }
  } catch (err) {
    console.error('获取用户信息失败：', err)
  }
}

// 获取有效优惠券数量
const getValidCouponCount = async () => {
  try {
    const token = uni.getStorageSync('token')
    const res = await couponApi.getCouponListByUserId(token)
    if (res.code === 200) {
      console.log('优惠券原始数据:', res.data)
      // 只统计未过期的优惠券
      const validCoupons = res.data.filter(item => {
        const now = new Date().getTime()
        const deadline = new Date(item.deadlineTime).getTime()
        const isExpired = deadline <= now
        console.log(`优惠券 ${item.couponName}: 截止时间=${item.deadlineTime}, 是否过期=${isExpired}`)
        return deadline > now // 只要没过期就计数
      })
      console.log('有效优惠券数量:', validCoupons.length)
      userInfo.value.couponCount = validCoupons.length
    }
  } catch (error) {
    console.error('获取优惠券数量失败:', error)
  }
}

let pollTimer = null;

// 页面加载时获取用户信息，并启动轮询
onMounted(() => {
  getMyInfo();
  pollTimer = setInterval(() => {
    getMyInfo(); // 这里会同时获取用户信息和更新优惠券数量
  }, 3000);
})

// 页面卸载时清除轮询
onUnmounted(() => {
  if (pollTimer) clearInterval(pollTimer);
})

// 定义页面生命周期
defineExpose({
  onShow() {
    getMyInfo()
  }
})
</script>

<style lang="scss" scoped>
.mine-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 32rpx;
}

.profile-section {
  display: flex;
  align-items: center;
  padding: 48rpx 32rpx 24rpx 32rpx;
  background: #fff;
  margin-bottom: 24rpx;
  
  .avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    margin-right: 24rpx;
    background: #eee;
    border: 4rpx solid #fff;
    box-shadow: 0 4rpx 8rpx rgba(0,0,0,0.1);
  }
  
  .user-info {
    display: flex;
    flex-direction: column;
    
    .nickname {
      font-size: 36rpx;
      color: #333;
      font-weight: 600;
      margin-bottom: 12rpx;
    }
  }
}

.member-card {
  margin: 0 32rpx 32rpx 32rpx;
  background: linear-gradient(135deg, #1b3c4b 0%, #2e5c6a 100%);
  border-radius: 24rpx;
  padding: 40rpx 32rpx 32rpx;
  color: #fff;
  box-shadow: 0 8rpx 16rpx rgba(0,0,0,0.1);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 40rpx;
    
    .card-type {
      font-size: 32rpx;
      font-weight: 600;
      margin-bottom: 12rpx;
      display: block;
    }
    
    .card-number {
      font-size: 24rpx;
      color: rgba(255,255,255,0.8);
      display: block;
    }
    
    .qr-icon {
      width: 64rpx;
      height: 64rpx;
      padding: 8rpx;
      background: rgba(255,255,255,0.1);
      border-radius: 12rpx;
    }
  }
  
  .card-info {
    display: flex;
    justify-content: center;
    align-items: stretch;
    min-height: 120rpx;
    background: none;
    margin: 0;
    padding: 0;

    .info-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 12rpx 0;
      border-radius: 0;
      transition: background-color 0.3s;
      min-width: 0;

      &:active {
        background-color: rgba(255, 255, 255, 0.1);
      }

      .info-value {
        font-size: 36rpx;
        font-weight: 600;
        margin-bottom: 8rpx;
      }

      .info-label {
        font-size: 24rpx;
        color: rgba(255,255,255,0.8);
      }
    }
  }
}

.section-title {
  font-size: 30rpx;
  color: #333;
  font-weight: 600;
  margin: 32rpx 32rpx 24rpx;
}

.feature-list {
  display: flex;
  flex-wrap: wrap;
  padding: 0 32rpx;
  background: #fff;
  border-radius: 16rpx;
  margin: 0 32rpx;
  
  .feature-item {
    width: 25%;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 32rpx 0;
    
    .feature-icon {
      width: 64rpx;
      height: 64rpx;
      margin-bottom: 16rpx;
    }
    
    text {
      font-size: 26rpx;
      color: #333;
    }
  }
}

.setting-list {
  background: #fff;
  border-radius: 16rpx;
  margin: 0 32rpx;
  
  .setting-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .setting-label {
      font-size: 28rpx;
      color: #333;
    }
    
    .setting-arrow {
      font-size: 28rpx;
      color: #999;
    }
  }
}

#png {
  width: 40px;
  height: 30px;
}
</style>